package com.jc.service.order;

import com.jc.cds.mapper.CustomXorderMapper;
import com.jc.cds.model.CustomXorder;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.WebUtils;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.base.service.BaseServiceImpl;
import com.jc.ds.model.OrderProducts;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderProcess;
import com.jc.framework.enums.OrderStatus;
import com.jc.service.model.yx.YanXuanResult;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@SuppressWarnings("all")
@Service
public class XorderServiceImpl extends BaseServiceImpl<Xorder, CustomXorder, Long> implements XorderService {

    @Autowired
    OrderProductsService OrderProductsService;

    @Autowired
    XorderMargeService xorderMargeService;

    @Autowired
    XorderProcessService xorderProcessService;

    @Autowired
    OrderProductsService orderProductsService;

    @Override
    public CustomXorderMapper getCustomMapper() {
        return (CustomXorderMapper) getBaseCustomMapper();
    }

    public List<CustomXorder> queryWaitPushOrder() {
        return this.getCustomMapper().queryWaitPushOrder();
    }

    @Override
    public Map<String, Object> queryAllLimit(Map<String, Object> xorder) {
        List<CustomXorder> customXorders = this.getCustomMapper().queryAllLimit(xorder);
        String count = "0";
        if (CollectionUtils.isNotEmpty(customXorders)) {
            count = customXorders.get(0).getCount();
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (CustomXorder c : customXorders) {
            Map<String, Object> stringObjectMap = WebUtils.beanToMap(c);
            stringObjectMap.put("id", stringObjectMap.get("id").toString());
            stringObjectMap.put("channelCreateTime", DateTimeUtil.getDate(c.getChannelCreateTime(), DateTimeUtil.LONG_TIME_FORMAT));

            for (OrderStatus orderStatus : OrderStatus.values()) {
                if (c.getOrderStatus().equals(orderStatus.getName())) {
                    stringObjectMap.put("orderStatusCH", orderStatus.getDesc());
                }
            }
//            if (OrderStatus.accept.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.accept.getDesc());
//            } else if (OrderStatus.outstorage.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.outstorage.getDesc());
//            } else if (OrderStatus.push_final.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.push_final.getDesc());
//            } else if (OrderStatus.push_ok.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.push_ok.getDesc());
//            } else if (OrderStatus.wait_push.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.wait_push.getDesc());
//            }else if (OrderStatus.tuiHuoIng.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.tuiHuoIng.getDesc());
//            } else if (OrderStatus.exit.getName().equals(c.getOrderStatus())) {
//                stringObjectMap.put("orderStatusCH", OrderStatus.exit.getDesc());
//            }
            resultList.add(stringObjectMap);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("data", resultList);
        result.put("count", count);
        result.put("code", 10000);
        result.put("msg", "");
        return result;
    }

    /**
     * 查询订单详情
     */
    @Override
    public Map<String, Object> queryOrderDetail(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        if (param.get("id") == null) {
            throw new BaseServiceException("订单Id不能为空");
        }
        //查询订单
        List<Xorder> xorders = this.queryAll(new Xorder() {{
            setId(Long.valueOf(param.get("id").toString()));
        }});
        if (CollectionUtils.isEmpty(xorders)) {
            throw new BaseServiceException("当前订单不存在");
        }
        Xorder xorder = xorders.get(0);
        Map<String, Object> xorderMap = WebUtils.beanToMap(xorder);
        if (OrderStatus.accept.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.accept.getDesc());
        } else if (OrderStatus.outstorage.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.outstorage.getDesc());
        } else if (OrderStatus.push_final.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.push_final.getDesc());
        } else if (OrderStatus.push_ok.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.push_ok.getDesc());
        } else if (OrderStatus.wait_push.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.wait_push.getDesc());
        } else if (OrderStatus.tuiHuoIng.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.tuiHuoIng.getDesc());
        } else if (OrderStatus.exit.getName().equals(xorder.getOrderStatus())) {
            xorderMap.put("orderStatusCH", OrderStatus.exit.getDesc());
        }
        result.put("orderDetail", xorderMap);
        //查询订单关联的产品
        List<OrderProducts> orderProducts = orderProductsService.queryAll(new OrderProducts() {{
            setOrderId(xorder.getId());
        }});
        if (CollectionUtils.isEmpty(orderProducts)) {
            throw new BaseServiceException("订单关联的产品不存在");
        }
        for (OrderProducts orderProduct : orderProducts) {
            if (orderProduct.getBalancePaidAmount() == null) {
                orderProduct.setBalancePaidAmount(0L);
            }
            if (StringUtils.isEmpty(orderProduct.getExpressNo())) {
                orderProduct.setExpressNo("暂无信息");
            }
            if (StringUtils.isEmpty(orderProduct.getExpressCompany())) {
                orderProduct.setExpressCompany("暂无信息");
            }
        }
        result.put("products", orderProducts);
        //查询订单操作明细
        List<XorderProcess> xorderProcesses = xorderProcessService.queryAll(new XorderProcess() {{
            setOrderId(xorder.getId());
            orderByProcessCreate(false);
        }});
        result.put("processes", xorderProcesses);
        return result;
    }


    @Transactional
    public void addOrder(Xorder order, List<OrderProducts> list) {
        if (order != null) {
            add(order, false);
            Long oid = order.getId();
            for (OrderProducts sku : list) {
                sku.setOrderId(oid);
                OrderProductsService.add(sku, false);
            }

        }
    }


    /**
     * 暂时有些问题，先不实现,因为OMS合并多个STORE_ID的订单推送到吉贡平台，
     * 如果多个STORE各自发货后，针对该笔合并订单会产生多个物流单号,但是目前该渠道回调整API只返回一条物流信息，
     * 需要和平台技术联系确认，这种情况的处理方式，后再进行实现。
     **/
    public YanXuanResult addOrderExpress(String channelOrderId, String expressName, String expressNo) {
		
		/*
		
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		
		//先查询有没有多次推送的临时订单号记录
		//查看有没有多次推送的记录，找到最后一次推送记录,关联到原订单号
		XorderMarge xorderMargeByChannelOrder = xorderMargeService.getXorderMargeByChannelOrderId(channelOrderId);
		String effectiveChannelOrderId = "";
		if(xorderMargeByChannelOrder == null) { //无重复推送记录
			effectiveChannelOrderId = channelOrderId;
		}else { //有记录
			effectiveChannelOrderId = xorderMargeByChannelOrder.getChannelOrderId();
		}
		//查询有没有合并订单的记录
		List<XorderMarge> childOrderList = xorderMargeService.getChildOrderList(effectiveChannelOrderId);
		String parentOrderId = null;
		List<Xorder> orderList = new ArrayList<Xorder>();
		
		if(CollectionUtils.isEmpty(childOrderList)) {//无合单记录
			Xorder queryOrder = new Xorder();
			queryOrder.setChannelOrderId(channelOrderId);
			queryOrder.setIsDelete(Booleans.FALSE.getName());
			List<Xorder> olist = queryAll(queryOrder);
			if(CollectionUtils.isEmpty(olist)) {
				ret.setCode(99999);
				ret.setMessage( channelOrderId +  " 订单不存在,无法出库");
				return ret;
			}
			if(olist.size() > 1) {
				ret.setCode(99999);
				ret.setMessage( channelOrderId +  " 订单在订单表存在两条以上记录,无法出库");
				return ret;
			}
			orderList = olist;
		}else {//有合单记录
			parentOrderId = channelOrderId;
			for(XorderMarge mg : childOrderList) {
				Long childOrderId = mg.getOrderId();
				orderList.add(queryById(childOrderId));
			}
		}
		
		
		
		// 现在每个子订单只有一个产品, 根据SKUID 比较后，更新子订单物流单号.
		String express_codes = "";
		for(Xorder o : orderList) {
			
			if(StringUtils.equals(o.getOrderStatus(),OrderStatus.outstorage.getName())) {
				//该条订单已出库跳过
				continue;
			}
			OrderProducts op = new OrderProducts();
		    op.setOrderId(o.getId());
			List<OrderProducts> oplist = orderProductsService.queryAll(op);
			if(CollectionUtils.isNotEmpty(oplist)) {
				String suppliper_product_id = oplist.get(0).getSupplierProductId();
				Map<String,Object> map = expressMap.get(suppliper_product_id);
				String expressNo = (String)map.get("expressNo");
				String expressCompany = (String)map.get("expressCompany");
				express_codes = express_codes  + expressNo + ",";
				//推送商城
				String code = shopService.pushOrder(o.getChannelOrderId());
				if(code != null && StringUtils.equals("0", code)) {
					o.setExpressNo(expressNo);
					o.setExpressName(expressCompany);
					o.setOrderStatus(OrderStatus.outstorage.getName());
					o.setUpdateTime(new Date());
					modify(o, false);
					xorderProcessService.addXorderProcess(o.getChannelOrderId(), "订单推送商城成功", SystemUser.ADMIN.getName(), o.getId());
				}else {
					xorderProcessService.addXorderProcess(o.getChannelOrderId(), "订单推送商城过程中发生错误,处理失败", SystemUser.ADMIN.getName(), o.getId());
				}
			}
		}
		
		if(StringUtils.isNotBlank(parentOrderId)) { //更新父订单的状态和运单号
			Xorder queryOrder = new Xorder();
			queryOrder.setChannelOrderId(parentOrderId);
			queryOrder.setIsDelete(Booleans.FALSE.getName());
			List<Xorder> olist = queryAll(queryOrder);
			if(CollectionUtils.isEmpty(olist)) {
				ret.setCode(99999);
				ret.setMessage( parentOrderId +  " 父订单不存在,无法出库");
				return ret;
			}
			if(olist.size() > 1) {
				ret.setCode(99999);
				ret.setMessage( parentOrderId +  " 父订单在订单表存在两条以上记录,无法出库");
				return ret;
			}
			Xorder updateOrder = olist.get(0);
			updateOrder.setOrderStatus(OrderStatus.outstorage.getName());
			updateOrder.setExpressNo(express_codes);
			updateOrder.setUpdateTime(new Date());
			modify(updateOrder, false);
		}
				
		*/

        return null;


    }


    /**
     * 6      * 时间戳转换成日期格式字符串
     * 7      * @param seconds 精确到秒的字符串
     * 8      * @param formatStr
     * 9      * @return
     * 10
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(seconds));
    }


    public void supplierCanelOrder(String orderId, String message) {
        Xorder order = this.queryById(Long.valueOf(orderId));
        if (order == null) {
            throw new BaseServiceException("订单不存在");
        }
        order.setOrderStatus(OrderStatus.tuiHuoIng.getName());
        if (StringUtils.isNotBlank(message)) order.setSellerMemo(message);
        this.modify(order, false);
    }


}
